import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/components/Layout.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '',
          name: 'Home',
          component: () => import('@/views/Home.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/courses',
          name: 'CourseList',
          component: () => import('@/views/CourseList.vue'),
          meta: { title: '课程管理' }
        },
        {
          path: '/courses/:id',
          name: 'CourseDetail',
          component: () => import('@/views/CourseDetail.vue'),
          meta: { title: '课程详情' }
        },
        {
          path: '/courses/:id/learn',
          name: 'CourseLearn',
          component: () => import('@/views/CourseLearn.vue'),
          meta: { title: '课程学习' }
        },
        {
          path: '/exams',
          name: 'ExamList',
          component: () => import('@/views/ExamList.vue'),
          meta: { title: '考试管理' }
        },
        {
          path: '/exams/:id',
          name: 'ExamDetail',
          component: () => import('@/views/ExamDetail.vue'),
          meta: { title: '考试详情' }
        },
        {
          path: '/learning',
          name: 'LearningCenter',
          component: () => import('@/views/LearningCenter.vue'),
          meta: { title: '学习中心' }
        },
        {
          path: '/profile',
          name: 'Profile',
          component: () => import('@/views/Profile.vue'),
          meta: { title: '个人中心' }
        },
        {
          path: '/settings',
          name: 'Settings',
          component: () => import('@/views/Settings.vue'),
          meta: { title: '系统设置' }
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/Register.vue'),
      meta: { title: '注册' }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const publicPaths = ['/login', '/register']
  
  if (!token && !publicPaths.includes(to.path)) {
    next('/login')
  } else {
    next()
  }
})

export default router